package com.lfs.feishu.service;

import com.alibaba.fastjson.JSON;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.service.im.ImService;
import com.lark.oapi.service.im.v1.model.P2MessageReadV1;
import com.lark.oapi.ws.Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;


import static com.lfs.feishu.constant.AppInfo.*;

@Service
@Slf4j
public class EventService {


    /**
     * {
     *     "reader": {
     *         "reader_id": {
     *             "user_id": "201511",
     *             "open_id": "ou_1d47c86409c47a0bc6abafaed3fa5968",
     *             "union_id": "on_b13ada6d91a3e7ef70df0fcdf66bbab9"
     *         },
     *         "read_time": "1761211585151",
     *         "tenant_key": "1b8d5fe6ea329758"
     *     },
     *     "message_id_list": [
     *         "om_x100b40ab0511a0cc0f1d53cd25f85c8"
     *     ]
     * }
     */
    @PostConstruct
    public void read() {
        // 构建 client Build client
        Client client = new Client.Builder(APP_ID, APP_SECRET)
                .eventHandler(EventDispatcher.newBuilder("HXtAmrPIapgZdwgGUDSqhdz2swN2Nd7Y", "mp1d71XsSc4qjHZtwZN4YeHHttW4H1Tx")
                        .onP2MessageReadV1(new ImService.P2MessageReadV1Handler() {
                            @Override
                            public void handle(P2MessageReadV1 event) {
                                P2MessageReadV1 messageRead = JSON.parseObject(JSON.toJSONString(event), event.getClass());
                                log.info("已读用户：{}", messageRead.getEvent().getReader().getReaderId().getUserId());
                                log.info("已读消息id：{}", JSON.toJSONString(messageRead.getEvent().getMessageIdList()));
                            }
                        }).build())
                .build();
        client.start();
    }

}
